﻿using Abp.Configuration.Startup;
using Abp.EntityFrameworkCore;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Zero;
using Castle.Windsor.MsDependencyInjection;
using Hengyuantong.SmartRail.Configuration;
using Hengyuantong.SmartRail.EntityFrameworkCore;
using Hengyuantong.SmartRail.Services.Implementations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Hengyuantong.SmartRail.Services
{
    [DependsOn(typeof(SmartRailCoreModule), typeof(SmartRailEntityFrameworkModule), typeof(Abp.Quartz.AbpQuartzModule))]
    public class HengyuantongServicesModule : AbpModule
    {

        readonly IConfigurationRoot _appConfiguration;

        public HengyuantongServicesModule(SmartRailEntityFrameworkModule smartRailEntityFrameworkModule)
        {
            smartRailEntityFrameworkModule.SkipDbSeed = true;
            var env = Environment.GetEnvironmentVariable("LONGFORRISK_SERVICES_ENVIRONMENT");
            _appConfiguration = AppConfigurations.Get(typeof(HengyuantongServicesModule).GetAssembly().GetDirectoryPathOrNull(), env);
        }

        public override void PreInitialize()
        {
            Configuration.BackgroundJobs.IsJobExecutionEnabled = true;
            Configuration.ReplaceService<IAppConfigurationAccessor, AppConfigurationAccessor>();

            var services = new ServiceCollection();

            services.AddAbpDbContext<SmartRailDbContext>(options =>
            {
                SmartRailDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
            });

            //IocManager.Register<IEventHubClient, EventHubClient>();

            //LogManager.LoadConfiguration("nlog.config");
            WindsorRegistrationHelper.CreateServiceProvider(IocManager.IocContainer, services);
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
            //Configuration.DefaultNameOrConnectionString = apolloClient.GetDecryptedConfigAsync("ConnectionStrings:Database").Result;
            Configuration.DefaultNameOrConnectionString = "Server=localhost;Database=SmartRailDb;User=sa;Password=123456;MultipleActiveResultSets=true;";
            //Configuration.Modules.UseRabbitMQ(options =>
            //{
            //    options.ConnectionString = apolloClient.GetDecryptedConfigAsync("ConnectionStrings:MQ").Result;
            //});

            //LogManager.Configuration.Variables["connectionstring"] = Configuration.DefaultNameOrConnectionString;
        }
    }
}
